package store

import (
	"HeadLineNews/settings"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
)

var db *sqlx.DB

// InitMySQLService 初始化 mysql 的链接
func InitMySQLService() {
	var err error
	if db, err = sqlx.Connect(
		"mysql",
		fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=%v&loc=%s",
			settings.Settings.MySQLConfig.UserName,
			settings.Settings.MySQLConfig.Password,
			settings.Settings.MySQLConfig.Host,
			settings.Settings.MySQLConfig.Port,
			settings.Settings.MySQLConfig.DB,
			settings.Settings.MySQLConfig.ParseTime,
			settings.Settings.MySQLConfig.Local,
		),
	); err != nil {
		log.Fatalf("connect mysql failed. error: %v\n", err)
	}
	db.SetMaxOpenConns(int(settings.Settings.MySQLConfig.MaxOpenConns)) // 设置最大连接数
	db.SetMaxIdleConns(int(settings.Settings.MySQLConfig.MaxIdleConns)) // 最大闲置连接数
	return
}

func DB() *sqlx.DB {
	return db
}
